package org.mspring.mlog.service.impl;

import java.util.List;

import org.mspring.mlog.entity.Link;
import org.mspring.mlog.service.LinkService;
import org.mspring.platform.dao.hibernate.GenericDao;
import org.mspring.platform.exception.BusinessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 
 * @author Gao Youbo
 * @since 2013-06-18 16:34:42
 */
@Service
@Transactional
public class LinkServiceImpl extends GenericDao<Link, java.lang.Long> implements LinkService {

    @Override
    public List<Link> findVisableLinks() {
        // TODO Auto-generated method stub
        return list("select link from Link link where link.visable = true order by link.order asc");
    }

    @Override
    public List<Link> findVisableLinks(Long linkType) {
        // TODO Auto-generated method stub
        String queryString = "select link from Link link where link.visable = true and link.type.id = ? order by link.order asc";
        return list(queryString, linkType);
    }

    @Override
    public void setLinkVisable(boolean visable, Long... id) {
        // TODO Auto-generated method stub
        if (id != null) {
            for (Long i : id) {
                executeUpdate("update Link l set l.visable = ? where l.id = ?", visable, i);
            }
        }
    }

    @Override
    public void updateLinkOrders(Long[] ids, Long[] orders) {
        // TODO Auto-generated method stub
        if (ids == null || orders == null || ids.length == 0 || orders.length == 0) {
            log.error("ids or orders is empty", new BusinessException("ids or orders is empty"));
            return;
        }
        if (ids.length != orders.length) {
            log.error("ids.length != orders.length", new BusinessException("ids.length != orders.length"));
            return;
        }
        for (int i = 0; i < ids.length; i++) {
            Long id = ids[i];
            Long order = orders[i];
            if (id == null) {
                log.warn("id is null");
                continue;
            }
            executeUpdate("update Link l set l.order = ? where l.id = ?", order, id);
        }
    }
}
